<template>
  <div style="width: 100%;" v-loading="loading">
    <div class="top-bar">
      <div class="item">
        <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 245px;height: 40px;"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="getData"/>
      </div>
      <div class="item">
        <el-select v-model="vibForm.featureType" placeholder="请选择">
          <el-option v-for="item in featureTypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </div>
      <div class="item">
        <el-select v-model="vibForm.physicalType">
          <el-option label="加速度" value="acc"/>
          <el-option label="速度" value="vel"/>
        </el-select>
      </div>
      <div class="item">
        <el-select v-model="vibForm.axial">
          <el-option v-for="item in featureAxialOptions" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </div>
    </div>
    <div class="chart-div" ref="chart"></div>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import {getLastDate, queryFeature} from "@/api/raw";
import {addDays} from "@/utils/common";

export default {
  name: 'FeatureChart',
  props: ['pointCode', 'axialOptions'],
  data() {
    return {
      loading: false,
      // 图表对象
      chart: null,
      // 图表配置
      chartOptions: null,
      // 图表数据
      chartData: null,
      chartDataName: null,
      // 折线图数据
      lineData: null,
      lineLegend: null,
      thresholdISO: null,
      timeList: null,
      colors: ["#28b1e4", "#0be188", "#fed129"],
      dateRange: [],
      featureAxialOptions: [],
      featureTypeOptions: [
        {
          value: 'rms',
          label: '有效值',
          unit: true
        },
        {
          value: 'kurt',
          label: '峭度',
          unit: false
        },
        {
          value: 'peak',
          label: '峰峰值',
          unit: true
        },
        {
          value: 'skew',
          label: '偏度',
          unit: false
        },
        {
          value: 'shapeFactor',
          label: '波形因子',
          unit: false
        },
        {
          value: 'crestFactor',
          label: '峰值因子',
          unit: false
        },
        {
          value: 'impulseFactor',
          label: '脉冲因子',
          unit: false
        },
        {
          value: 'clearanceFactor',
          label: '裕度因子',
          unit: false
        },
        {
          value: 'avgAbs',
          label: '整流平均值',
          unit: true
        },
        // {
        //   value: 'lowEnergy',
        //   label: '低频能量值',
        //   unit: true
        // },
        // {
        //   value: 'highEnergy',
        //   label: '高频能量值',
        //   unit: true
        // }
      ],
      vibForm: {
        pointCode: null,
        featureType: "rms",
        physicalType: "acc",
        axial: "x",
      }
    }
  },
  watch: {
    pointCode: {
      handler: function (val) {
        this.$nextTick(() => {
          this.vibForm.pointCode = val;
          this.getLastDate();
        })
      },
      immediate: true
    },
    vibForm: {
      handler: function (val) {
        this.$nextTick(() => {
          this.setAxial();
          this.getData();
        })
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', () => {
      this.chart.resize()
    })
  },
  methods: {
    async getLastDate() {
      if (!this.pointCode) {
        this.getData();
        return;
      }
      let res = await getLastDate(this.pointCode);
      if (res.data != null) {
        let endTime = this.parseTime(res.data, '{y}-{m}-{d}');
        let beginTime = this.parseTime((res.data - 3600 * 1000 * 1000 * 24 * 30), '{y}-{m}-{d}');
        this.dateRange = [beginTime, endTime];
      } else {
        const today = new Date();
        this.dateRange = [this.parseTime(addDays(today, -7).getTime(), '{y}-{m}-{d}'), this.parseTime(today.getTime(), '{y}-{m}-{d}')];
      }
      this.getData();
    },
    getData() {
      this.loading = true;
      this.lineColors = []
      this.chartDataName = [];
      this.lineData = [];
      this.lineLegend = [];
      this.thresholdISO = null;
      this.timeList = [];
      if (!this.vibForm.pointCode) {
        this.loadData(this.vibForm.axial);
        return;
      }
      if (this.isNullOrEmpty(this.dateRange)) return;
      let queryParams = this.addDateRange(this.vibForm, this.dateRange);
      let selectP = [];
      let featureData = this.getFeatureData(queryParams);
      selectP.push(featureData);
      // 使用 Promise.all 来并行执行多个async请求
      Promise.all(selectP).then(res => {
        this.loadData(this.vibForm.axial);
      });
    },
    /**
     * 查询特征值
     * @param queryParams
     */
    async getFeatureData(queryParams) {
      this.chartData = [];
      let res = await queryFeature(queryParams);
      if (!res.data) return;
      this.setEventTime(res.data.eventTime);
      if (this.vibForm.axial === 'overall') {
        //查询综合曲线
        if (res.data.overall) {
          let oArray = [];
          for (let i in res.data.eventTime) {
            let ts = res.data.eventTime[i];
            oArray.push([ts, res.data[this.vibForm.axial][i]]);
          }
          this.chartData.push(oArray);
          this.chartDataName.push("综合");
        } else {
          this.chartData = [];
        }
      } else {
        // 查询全部 XYZ 或者 单独方向的数据
        // let axialArr = this.featureForm.axial.split('');
        let axialArr = this.getAxialValue().split('');
        for (let axial of axialArr) {
          let dataAxial = [];
          for (let i in res.data.eventTime) {
            let ts = res.data.eventTime[i];
            dataAxial.push([ts, res.data[axial][i]])
          }
          if (this.isNullOrEmpty(dataAxial)) continue;
          this.chartData.push(dataAxial);
          let axialName = this.getAxialName(axial);
          let featureName = this.featureTypeOptions.filter(item => item.value === this.vibForm.featureType)[0].label;
          this.chartDataName.push(axialName + featureName);
        }
      }
    },
    //选择最长的时间作为时间列表
    setEventTime(timeList) {
      if (this.timeList) {
        this.timeList = this.timeList.length > timeList.length ? this.timeList : timeList;
      } else {
        this.timeList = timeList;
      }
    },
    //设置测点轴向信息
    setAxial() {
      this.featureAxialOptions = [];
      this.featureAxialOptions.push({
        value: 'xyz',
        label: '全部'
      });
      for (let key in this.axialOptions) {
        let obj = {
          value: this.axialOptions[key].value,
          label: this.axialOptions[key].label
        }
        this.featureAxialOptions.push(obj);
      }
      if (this.vibForm.featureType === 'rms') {
        this.featureAxialOptions.push({
          value: 'overall',
          label: '综合'
        });
      }
      if (!this.featureAxialOptions.some(l => l.value === this.vibForm.axial)) {
        this.vibForm.axial = this.featureAxialOptions[1].value;
      }
    },
    //设置xyz对应的名称
    getAxialName(val) {
      const item = this.axialOptions.find(item => item.value === val);
      return item ? item.label : null;
    },
    getAxialValue() {
      if (['x', 'y', 'z'].includes(this.vibForm.axial)) {
        return this.vibForm.axial
      }
      const allOptions = this.axialOptions.map(obj => obj.value);
      const filteredOptions = allOptions.filter(value => value !== 'xyz' && value !== 'overall');
      return filteredOptions.join('');
    },
    /**
     * 加载图表
     * @param axial
     */
    loadData(axial) {
      let showUnit = this.featureTypeOptions.filter(l => l.value === this.vibForm.featureType)[0].unit;
      let yName = showUnit ? this.vibForm.physicalType === 'acc' ? 'g' : 'mm/s' : '';
      if (this.isNullOrEmpty(this.chartData) && this.isNullOrEmpty(this.lineData)) {
        this.lineLegend = [];
        this.timeList = [];
        this.chartOptions.yAxis[0].name = yName;
        this.chartOptions.xAxis[0].data = [];
        this.chartOptions.series = [];
        this.chart.setOption(this.chartOptions, true);
        this.chart.showLoading({
          text: '暂无数据',
          showSpinner: false,
          textColor: '#808080',
          maskColor: 'rgba(0, 0, 0, .2)',
          fontSize: '26px',
          fontWeight: '400'
        })
        this.loading = false;
      } else {
        // let option = this.chart.getOption();
        let series = [];
        // 散点图参数数据
        if (!this.isNullOrEmpty(this.chartData)) {
          for (let i in this.chartData) {
            let obj = {
              type: 'scatter',
              name: this.chartDataName[i],
              symbolSize: 10,
              data: this.chartData[i]
            }
            series.push(obj);
          }
        }
        let maxValue = undefined;
        // 折线图数据
        if (!this.isNullOrEmpty(this.lineData)) {
          for (let j in this.lineData) {
            if (this.thresholdISO) {
              const flatArr = this.lineData[j].map(item => item[1]);
              const maxVal = Math.max(...flatArr)
              if (this.thresholdISO > maxVal) {
                // option.yAxis[0].max = this.thresholdISO;
                maxValue  = this.thresholdISO
              }
              let obj = {
                type: 'line',
                name: this.lineLegend[j],
                symbol: "none",
                smooth: true,
                data: this.lineData[j],
                connectNulls: false,
                markLine: {
                  data: [{
                    name: 'ISO阈值',
                    yAxis: this.thresholdISO
                  }],
                  lineStyle: {
                    color: 'red',
                    opacity: 1
                  },
                  label: {
                    color: 'red'
                  }
                }
              }
              series.push(obj);
            } else {
              let obj = {
                type: 'line',
                itemStyle: {
                  //color: '#91cc75'
                  color: this.lineColors[j]
                },
                name: this.lineLegend[j],
                symbol: "none",
                smooth: true,
                data: this.lineData[j]
              }
              series.push(obj);
            }
          }
        }
        this.chartOptions.yAxis[0].max = maxValue;
        this.chartOptions.yAxis[0].name = yName;
        this.chartOptions.xAxis[0].data = this.timeList;
        this.chartOptions.series = series;
        //解决markline不显示问题
        this.chartOptions.markLine = undefined;
        this.chart.setOption(this.chartOptions, true);
        this.chart.hideLoading();
        this.loading = false;
      }
    },
    /**
     * 初始化图表
     */
    initChart: function () {
      if (this.chart !== null && this.chart !== undefined) {
        this.chart.dispose();
      }
      this.chartOptions = {
        color: [
          "#28b1e4",
          "#91cc75",
          "#fac858",
          "#ee6666",
          "#73c0de",
          "#3ba272",
          "#fc8452",
          "#9a60b4",
          "#ea7ccc"
        ],
        title: {
          text: '',
          textStyle: {
            fontStyle: '',
            color: '#f7f9fa',
            fontWeight: 'normal',
            fontSize: 16
          },
          left: 30
        },
        legend: {
          textStyle: {}
        },
        toolbox: {
          show: true,
          height: 0,
          top: -5,
          right: 10,
          feature: {},
          itemSize: 18,
          iconStyle: {
            borderColor: '#fffbfb'
          }
        },
        dataZoom: [{
          type: 'inside',
          show: true
        }],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          crossStyle: {
            color: '#999'
          },
          showContent: true
        },
        xAxis: [
          {
            position: 'bottom',
            name: '时间 - s',
            nameLocation: 'center',
            nameTextStyle: {
              padding: [10, 0, 0, 0]
            },
            type: 'category',
            //横坐标标注线
            axisTick: {
              alignWithLabel: true,
              lineStyle: {
                color: '#3c3f41'
              },
            },
            //横坐标标注
            axisLine: {
              show: true,
              lineStyle: {
                color: '#202c3a'
              }
            },
            splitLine: {
              lineStyle: {
                color: '#c6c6c6'
              }
            },
            axisPointer: {
              show: true,
              lineStyle: {
                color: '#E6A23C'
              },
              label: {
                backgroundColor: '#E6A23C'
              }
            },
            axisLabel: {
              show: true
            }
          }
        ],
        yAxis: [
          {
            name: 'g',
            nameLocation: 'end',
            nameTextStyle: {
              align: 'left',
            },
            type: 'value',
            boundaryGap: ['20%', '20%'],
            splitLine: {
              lineStyle: {
                color: '#f0f0f0'
              }
            },
            //纵坐标线及刻度
            axisLine: {
              show: true,
              lineStyle: {
                color: '#202c3a'
              }
            },
            axisLabel: {
              inside: false
            },
            axisPointer: {
              lineStyle: {
                color: '#E6A23C'
              },
              label: {
                backgroundColor: '#E6A23C'
              }
            },
            axisTick: {
              inside: true
            }
          }
        ],
        grid: {
          top: 40,
          bottom: 20,
          left: 8,
          right: 16,
          containLabel: true
        },
        series: []
      };
      // 创建新的 echarts 实例
      this.chart = echarts.init(this.$refs.chart);
      this.chart.setOption(this.chartOptions);
      let that = this;
      onOrientationChange(function () {
        that.chart.resize()
      })
    },
  }
}
var onOrientationChange = function (cb) {
  var evt = 'onorientationchange' in window ? 'orientationchange' : 'resize'
  window.addEventListener(evt, resize, true)

  function resize(fals) {
    if (window.orientation === 0 || window.orientation === 180) {
      cb('v')
    } else {
      cb('h')
    }
  }

  resize(true)
}
</script>
<style scoped>
.chart-div {
  width: 100%;
  height: 350px;
}

.top-bar {
  margin-bottom: 20px !important;
  display: flex;
}

.top-bar > .item {
  margin: 0 0 0 10px;
}

.top-bar > .item .el-select {
  width: 245px;
}
</style>